import time
import os
from selenium.webdriver.chrome import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from utils.until_wx import Until
from db.dbbase import DBBase
from db.models import WxLoginQcode
#from selenium.common.exceptions import NoSuchElementException

until = Until()
dbbase = DBBase()


'''
初始化浏览器,用于登陆获取cookies
'''

def init_brower():
    # 配置chrome浏览器的驱动
    chrome_driver_file = os.path.abspath(r"C:\Program Files\tool\chormDriver\chromedriver.exe")
    os.environ["webdriver.chrome.driver"] = chrome_driver_file
    option = Options()
    option.binary_location = 'D:\ChromePortable\ChromePortable.exe'
    # option.add_argument('--user-data-dir=' + 'D:\chromDataAll\data2')
    user_agent = until.random_useragent()
    option.add_argument('--user-agent=' + user_agent)  # 随机获取一个user_agent
    browser = webdriver.WebDriver(executable_path=chrome_driver_file, chrome_options=option)
    browser.get('http://weixin.sogou.com/')
    return browser
'''
检查是否登陆
'''
def checkislogin(browser):
    time.sleep(1)
    try:
        logintext = browser.find_element_by_xpath('//*[@id="login_yes"]/a').text
        if logintext == '':
            return False
        return True
    except:
        return False

def wx_login(adminid, requstuuid):
    browser = init_brower()
    time.sleep(1)
    try:
        browser.find_element_by_xpath('//*[@id="loginBtn"]').click()
    except:
        browser.close()
        browser = init_brower()
        browser.find_element_by_xpath('//*[@id="loginBtn"]').click()
    time.sleep(1)
    browser.switch_to.frame(0)
    time.sleep(1)
    iframetext = browser.page_source
    iframetsoup = BeautifulSoup(iframetext, 'xml')
    codeurl_src = iframetsoup.find('img', {'class': 'qrcode lightBorder'})['src']
    codeurl = 'https://open.weixin.qq.com' + codeurl_src
    wxloginqcode = WxLoginQcode()
    # print(adminid,requstuuid, codeurl)
    wxloginqcode.adminid = adminid
    wxloginqcode.requstuuid = requstuuid
    wxloginqcode.codeurl = codeurl
    wxloginqcode.cookies = '0'
    data = eval('{'+str(wxloginqcode)+'}')
    dbbase.insert_wx_qcode(data)
    time.sleep(40)
    if checkislogin(browser): # 检测浏览器是否登陆
        cookies = browser.get_cookies()
        dbbase.insert_wx_cookies(adminid, requstuuid, cookies)
    browser.close()

if __name__=='__main__':
    wx_login('123','123312312-43345wqe-qwdfasd123')